24. Exercise: Button States and SnackBar
L6 49 Button States SC
L6 50 Snackbar SC
Update:
In the video above, thesleepTrackerViewModel.showSnackBarEvent.observe()function in theSleepTrackerFragment.ktfile, :
- the first argument should be
viewLifecycleOwnerinstead of the current objectthis.- The
activity!!.findViewById(android.R.id.content)has been updated torequireActivity().findViewById(android.R.id.content).
Now it's your turn to complete this exercise yourself.
In this step, you'll add states to show and hide the buttons, and use a SnackBar to notify the user when they clear the data.
Button States
Open
fragment_sleep_tracker.xml.Add the
enabledproperty to each button, and give it the value of a state variable:
android:enabled="@{sleepTrackerViewModel.startButtonVisible}"
android:enabled="@{sleepTrackerViewModel.stopButtonVisible}"
android:enabled="@{sleepTrackerViewModel.clearButtonVisible}"
Open
SleepTrackerViewModel.ktand create three corresponding variables.Assign them a
Transformationsthat tests it against the value oftonight.The START button should be
visiblewhentonightis null, the STOP button whentonightis not null, and the CLEAR button ifnightscontains anynights:
val startButtonVisible = Transformations.map(tonight) {
null == it
}
val stopButtonVisible = Transformations.map(tonight) {
null != it
}
val clearButtonVisible = Transformations.map(nights) {
it?.isNotEmpty()
}
- Run your app, and that's all there is to it!
Snackbar
Use the same pattern as for navigation to set up and trigger a snackbar when the data is cleared.
- In the
SleepTrackerViewModel, create the encapsulated event:
private var _showSnackbarEvent = MutableLiveData<Boolean>()
val showSnackBarEvent: LiveData<Boolean>
get() = _showSnackbarEvent
- Then implement
doneShowingSnackbar():
fun doneShowingSnackbar() {
_showSnackbarEvent.value = false
}
- In the
SleepTrackerFragment, add an observer:
sleepTrackerViewModel.showSnackBarEvent.observe(viewLifecycleOwner, Observer { })
- Display the snackbar and immediately reset the event:
if (it == true) { // Observed state is true.
Snackbar.make(
requireActivity().findViewById(android.R.id.content),
getString(R.string.cleared_message),
Snackbar.LENGTH_SHORT // How long to display the message.
).show()
sleepTrackerViewModel.doneShowingSnackbar()
}
- To trigger the event, in
onClear(), set the event value totrue:
_showSnackbarEvent.value = true
- Build and run your app!
If you want to start at this step, you can download this exercise from: Step.07-Exercise-Add-Button-States-and-SnackBar.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here: Step.07-Add-Button-States-and-SnackBar, or using this git diff.
Task Feedback:
Congratulations! This lesson introduced coroutines and other more advanced topics, and you've completed it all.
Reference Documentation